package games.openarena;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;

import utils.MyUtils;

public class LogSplitter {

	private static final String logOrig = "/home/gmarcone/Descargas/openarena_logs/20120709_JP.log";
	private static int fileCount = 0;

	public static void main(String[] args) {
		try {
			BufferedReader leer = new BufferedReader(new InputStreamReader(new FileInputStream(logOrig)));

			int maxBytes = 4194304; //4mb

			StringBuilder writeString = new StringBuilder();

			while (leer.ready()) {
				String leerJuego = leerJuego(leer);

				if (writeString.length() + leerJuego.length() > maxBytes) {
					write(writeString.toString());
					writeString = new StringBuilder();
				}

				writeString.append(leerJuego).append(MyUtils.EOL);
			}

			write(writeString.toString());

		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}


	private static void write(String string) throws IOException {
		Writer wr = new FileWriter("/home/gmarcone/Descargas/openarena_logs/20120709_JP_" + fileCount +".log");
		fileCount++;
		wr.write(string);
		wr.flush();
		wr.close();
	}

	private static String leerJuego(BufferedReader leer) throws IOException {
		String linea;
		StringBuilder writeString = new StringBuilder();
		boolean fin = false;
		while (!fin && (linea = leer.readLine()) != null) {

			writeString.append(linea).append(MyUtils.EOL);

			if (linea.contains("ShutdownGame")) {
				writeString.append(leer.readLine());
				fin = true;
			}
		}

		if (!fin) {
			leer.close();
		}

		return writeString.toString();
	}
}
